#coding=utf-8
class dbConnect:
    def __init__(self):
        pass
    def __enter__(self):
        import sqlite3
        self.conn = sqlite3.connect("starmsg.db")
        self.cs = self.conn.cursor()
        return self.cs
    def __exit__(self,exc_type,exc_cal,exc_tb):
        self.conn.commit()
        self.conn.close()

def encodeMD5(str):
    import hashlib
    m = hashlib.md5()
    m.update(str.encode(encoding='UTF-8'))
    return m.hexdigest()

def checkPsw(id, psw):
    with dbConnect() as cs:
        cs.execute("select * from username where id = ? and password = ?",(id,encodeMD5(psw)))
        result = cs.fetchall()

    ans = {"check":False,"info":{}}
    if len(result):
        ans["check"] = True
        result = result[0]
        ans["info"] = {
            "id": result[0],
            "nickname": result[1],
            "gender": result[3],
            "avatar": result[4],
            "otherinfo":result[5]
        }
    return ans

def userlist():
    with dbConnect() as cs:
        cs.execute("select * from username")
        result = cs.fetchall()
    return [res[:2] for res in result]  
    

def addUsr(info):
    with dbConnect() as cs:
        cs.execute("select id from username where id=?",(info["id"],))
        if len(cs.fetchall()):
            return {"check":False,"info":"id已经注册"}
        cs.execute("insert into username values (?,?,?,?,?,?)",(
            info["id"],
            info["nickname"],
            encodeMD5(info["password"]),
            info["gender"],
            info["avatar"],
            info["otherinfo"]))
    return {"check":True,"info":"注册成功"}

def updateUsr(info):
    with dbConnect() as cs:
        cs.execute("select id from username where id=?",(info["id"],))
        cs.execute("update username \
            set nickname=?, gender=?, avatar=?, otherinfo=?\
            where id=?",(
                info["nickname"],
                info["gender"],
                info["avatar"],
                info["otherinfo"],
                info["id"]))
    return {"check":True,"info":info}

def changePsw(info):
    with dbConnect() as cs:
        cs.execute("select id from username where id=?",(info["id"],))
        cs.execute("update username \
            set password=?\
            where id=?",(encodeMD5(info["password"]),info["id"]))
    return {"check":True,"info":info}

def getUserInfo():
    with dbConnect() as cs:
        cs.execute("select id,nickname,avatar from username")
        result = cs.fetchall()
    return result

def sendChart(info):
    id1 = info['id1']
    id2 = info['id2']
    msg = info['msg']
    ref = info['ref']
    if "unkown" in [id1,id2]:
        return
    with dbConnect() as cs:
        import time
        cs.execute("insert into chartlog values (?,?,?,?,?)",(
            id1,id2,msg,int(time.time()*1000),ref))
def getChart(id1,id2,num):
    with dbConnect() as cs:
        cs.execute("select source,content,time,ref from chartlog where (source=? and target=?) or (source=? and target=?)\
            order by time limit ?",(id1,id2,id2,id1,num))
        result = cs.fetchall()
    return result